/* File to test simple context level task switching */

#include <tr_port.h>
#include "proj_config.h"
#include "util.h"


#define NUM_TASKS  5
#define TSK_STKSIZE	(TRPORT_MIN_CTXT_SZ + 64)

osword_t task_stk[NUM_TASKS][TSK_STKSIZE];
osword_t*    task_stk_ptr[NUM_TASKS];

volatile int curr_task = 0;

uint8_t osint_alarm_reached(const trtime_t * t )
{
	return 0;
}


osword_t* osint_taskswitcher(osword_t *stkptr)
{
	task_stk_ptr[curr_task] = stkptr;
	curr_task++;
	if (curr_task == NUM_TASKS)
		curr_task = 0;
	putstring("Switching: "); puthexchar(curr_task); putchar('\n');
	return task_stk_ptr[curr_task];
}

osword_t* osint_running_task_ctxt(void)
{
	return task_stk_ptr[curr_task];
}

void print_trtime(const trtime_t * t)
{
	uint32_t sec = t->units;
	uint32_t subunits = t->subunits;
	putchar('0'); putchar('x');
	puthexint(sec, 4);
	putchar(':');
	puthexint(subunits, sizeof(t->subunits));
}


void task(void * dummy)
{
	int myid = (int)(dummy);

	while (1) {                         //main loop, never ends...
		putstring("Hello World from task : ");
		puthexchar((unsigned char) myid);
		putchar('\n');
		delayms(1000);
		hal_ctxt_switch();
	}
}

/* Implement in platform_xxx.c . To do any extra initialization, such
 * as serial port setup */
void platform_init(void);

int main(void) 
{
	int i;

	platform_init();

	hal_init();
	for (i=0; i< NUM_TASKS; i++) {
		task_stk_ptr[i] = hal_stk_init(task_stk[i],
					       TSK_STKSIZE, 
					       task,
					       (osptr_t)i);
	}
	

	hal_ctxt_load( task_stk_ptr[0]);

	putstring("Main: Should not reach here\n");
	return 0;
}

